//	---------------------------------------------------------------------------
//	jWebSocket - WebSoocket Demo MIDlet
//	Copyright (c) 2010 Alexander Schulze, Innotrade GmbH
//	---------------------------------------------------------------------------
//	This program is free software; you can redistribute it and/or modify it
//	under the terms of the GNU Lesser General Public License as published by the
//	Free Software Foundation; either version 3 of the License, or (at your
//	option) any later version.
//	This program is distributed in the hope that it will be useful, but WITHOUT
//	ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//	FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
//	more details.
//	You should have received a copy of the GNU Lesser General Public License along
//	with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
//	---------------------------------------------------------------------------
package com.msstudio.midlets;

import com.msstudio.message.MessageSender;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import com.msstudio.websocket.client.api.WebSocketClientListener;
import com.msstudio.websocket.client.api.WebSocketPacket;
import com.msstudio.websocket.client.exception.WebSocketException;
import com.msstudio.websocket.client.event.WebSocketClientEvent;
import com.msstudio.websocket.client.WebSocketClient;
import javax.microedition.pim.*;
import java.util.Enumeration;

/**
 * @author aschulze
 */
public class IndiKikClient extends MIDlet implements CommandListener, WebSocketClientListener, ItemCommandListener, ItemStateListener {

    private boolean midletPaused = false;
    private WebSocketClient websocketClient = null;
    private MessageSender mMsgSender = null;
    private int prevStatus = WebSocketClient.DISCONNECTED;
//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command cmdExit;
    private Command cmdConnect;
    private Command cmdDisconnect;
    private Command cmdLogin;
    private Command cmdLogout;
    private Command cmdSend;
    private Command cmdBroadcast;
    private Command cmdSetup;
    private Command cmdOk;
    private Command cmdCamera;
    private Command cmdSendMsg;
    private Command backCommand;
    private Command cmdUploadContactList;
    private Form frmDemo;
    private StringItem stiLog;
    private TextField txfTarget;
    private TextField txfURL;
    private ImageItem imgStatus;
    private StringItem connectButton;
    private Spacer spacer1;
    private Form MsgFrm;
    private Spacer spacer;
    private StringItem ConversationBox;
    private TextField InMsg;
    private StringItem UploadContactList;
    private Image imgDisconnected;
    private Image imgConnected;
    private Image imgAuthenticated;
//</editor-fold>//GEN-END:|fields|0|
     
    /**
     * The JWebSocketJavaMEDemo constructor.
     */
    public IndiKikClient() {
    }

    private void checkStatusIcon() {
        /* int lStatus = BaseClientJ2ME.DISCONNECTED;
        if (websocketClient.getUsername() != null) {
            lStatus = BaseClientJ2ME.AUTHENTICATED;
        } else if (websocketClient.isConnected()) {
            lStatus = BaseClientJ2ME.CONNECTED;
        }
        if (lStatus != prevStatus) {
            prevStatus = lStatus;
            if (lStatus == TokenClient.AUTHENTICATED) {
                imgStatus.setImage(getImgAuthenticated());
            } else if (lStatus == TokenClient.CONNECTED) {
                imgStatus.setImage(getImgConnected());
            } else {
                imgStatus.setImage(getImgDisconnected());
            }
        } */
    }
    
    public void itemStateChanged(Item item){

            System.out.println(InMsg.getString());

    }

    public void processOpened(WebSocketClientEvent aEvent) {
        stiLog.setText("Connection opened.");
        checkStatusIcon();        
    }

    public void processPacket(WebSocketClientEvent aEvent, WebSocketPacket aPacket) {
        if (aPacket.getFrameType() == WebSocketPacket.FRAMETYPE_UTF8) {
            stiLog.setText("received a text frame, length:" + aPacket.getFrameLength() + " --" + aPacket.getString());
        } else {
            stiLog.setText("received a binary frame, length:" + aPacket.getFrameLength());
            byte[] msg = aPacket.getByteArray();
            for (int i = 0; i < msg.length; i++)
            {
                System.out.print(msg[i]);
		System.out.print(" ");
            }
            System.out.println("");
        }
        checkStatusIcon();
    }

    public void processClosed(WebSocketClientEvent aEvent) {
        stiLog.setText("Connection closed.");
        switchDisplayable(null, getFrmDemo());
        checkStatusIcon();
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initializes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
        websocketClient = new WebSocketClient();
        mMsgSender = new MessageSender(websocketClient);
        websocketClient.addListener(this);
    }//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getFrmDemo());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
		boolean connetStatus = true;
        if (displayable == MsgFrm) {//GEN-BEGIN:|7-commandAction|1|62-preAction
            if (command == backCommand) {//GEN-END:|7-commandAction|1|62-preAction
                // write pre-action user code here
                switchDisplayable(null, getMsgFrm());//GEN-LINE:|7-commandAction|2|62-postAction
                // write post-action user code here
                websocketClient.close();
            }//GEN-BEGIN:|7-commandAction|3|33-preAction
        } else if (displayable == frmDemo) {
            if (command == cmdBroadcast) {//GEN-END:|7-commandAction|3|33-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|4|33-postAction
                // write post-action user code here
                /* try {
                    websocketClient.broadcastText(txfMessage.getString());
                } catch (WebSocketException ex) {
                    stiLog.setText(ex.getMessage());
                } */
            } else if (command == cmdCamera) {//GEN-LINE:|7-commandAction|5|53-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|6|53-postAction
                // write post-action user code here
                Camera lCamera = new Camera(websocketClient, this, frmDemo);

            } else if (command == cmdConnect) {//GEN-LINE:|7-commandAction|7|23-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|8|23-postAction
                // write post-action user code here
                try {
                    websocketClient.open(txfURL.getString(), "/websocket");
                } catch (WebSocketException ex) {
                    stiLog.setText(ex.getMessage());
                }
                
            } else if (command == cmdDisconnect) {//GEN-LINE:|7-commandAction|9|25-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|10|25-postAction
                // write post-action user code here
                websocketClient.close();
            } else if (command == cmdExit) {//GEN-LINE:|7-commandAction|11|19-preAction
                // write pre-action user code here
                websocketClient.close();
                exitMIDlet();//GEN-LINE:|7-commandAction|12|19-postAction
                // write post-action user code here
            } else if (command == cmdLogin) {//GEN-LINE:|7-commandAction|13|27-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|14|27-postAction
                // write post-action user code here  
				connetStatus = mMsgSender.sendLoginMessage("sunny", "test");
            } else if (command == cmdLogout) {//GEN-LINE:|7-commandAction|15|29-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|16|29-postAction
                // write post-action user code here
                // Todo: websocketClient.logout();
            } else if (command == cmdSend) {//GEN-LINE:|7-commandAction|17|31-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|18|31-postAction
                // write post-action user code here                                
                /* try {
                    byte[] sendBuf = new byte[268];
                    sendBuf[0] = 0x00;
                    sendBuf[1] = (byte) 0xff;
                    for (int i = 0; i < sendBuf.length - 2; i++) {
                        sendBuf[i + 2] = (byte) i;
                    }
                    websocketClient.send(sendBuf);
                    sendBuf = null;
                    websocketClient.send("this is a test 中文测试");                    
                } catch (WebSocketException ex) {
                    stiLog.setText(ex.getMessage());
                } */
                switchDisplayable(null, getMsgFrm());
            } else if (command == cmdSetup) {//GEN-LINE:|7-commandAction|19|38-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|20|38-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|21|7-postCommandAction
        }//GEN-END:|7-commandAction|21|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|22|
//</editor-fold>//GEN-END:|7-commandAction|22|


    //</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdExit ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initiliazed instance of cmdExit component.
     * @return the initialized component instance
     */
    public Command getCmdExit() {
        if (cmdExit == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            cmdExit = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return cmdExit;
    }
//</editor-fold>//GEN-END:|18-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: frmDemo ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initiliazed instance of frmDemo component.
     * @return the initialized component instance
     */
    public Form getFrmDemo() {
        if (frmDemo == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            frmDemo = new Form("jWebSocket Fundamental Demo", new Item[]{getConnectButton(), getSpacer1(), getTxfURL(), getTxfTarget(), getImgStatus(), getStiLog()});//GEN-BEGIN:|14-getter|1|14-postInit
            frmDemo.addCommand(getCmdExit());
            frmDemo.addCommand(getCmdConnect());
            frmDemo.addCommand(getCmdDisconnect());
            frmDemo.addCommand(getCmdLogin());
            frmDemo.addCommand(getCmdLogout());
            frmDemo.addCommand(getCmdSend());
            frmDemo.addCommand(getCmdBroadcast());
            frmDemo.addCommand(getCmdSetup());
            frmDemo.addCommand(getCmdCamera());
            frmDemo.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return frmDemo;
    }
//</editor-fold>//GEN-END:|14-getter|2|
    //</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stiLog ">//GEN-BEGIN:|16-getter|0|16-preInit
    /**
     * Returns an initiliazed instance of stiLog component.
     * @return the initialized component instance
     */
    public StringItem getStiLog() {
        if (stiLog == null) {//GEN-END:|16-getter|0|16-preInit
            // write pre-init user code here
            stiLog = new StringItem("", "...", Item.PLAIN);//GEN-BEGIN:|16-getter|1|16-postInit
            stiLog.setLayout(ImageItem.LAYOUT_DEFAULT | Item.LAYOUT_EXPAND | Item.LAYOUT_VEXPAND | Item.LAYOUT_2);//GEN-END:|16-getter|1|16-postInit
            // write post-init user code here
        }//GEN-BEGIN:|16-getter|2|
        return stiLog;
    }
//</editor-fold>//GEN-END:|16-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdConnect ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initiliazed instance of cmdConnect component.
     * @return the initialized component instance
     */
    public Command getCmdConnect() {
        if (cmdConnect == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            cmdConnect = new Command("Connect", Command.ITEM, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
        }//GEN-BEGIN:|22-getter|2|
        return cmdConnect;
    }
//</editor-fold>//GEN-END:|22-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdDisconnect ">//GEN-BEGIN:|24-getter|0|24-preInit
    /**
     * Returns an initiliazed instance of cmdDisconnect component.
     * @return the initialized component instance
     */
    public Command getCmdDisconnect() {
        if (cmdDisconnect == null) {//GEN-END:|24-getter|0|24-preInit
            // write pre-init user code here
            cmdDisconnect = new Command("Disconnect", Command.ITEM, 0);//GEN-LINE:|24-getter|1|24-postInit
            // write post-init user code here
        }//GEN-BEGIN:|24-getter|2|
        return cmdDisconnect;
    }
//</editor-fold>//GEN-END:|24-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdLogin ">//GEN-BEGIN:|26-getter|0|26-preInit
    /**
     * Returns an initiliazed instance of cmdLogin component.
     * @return the initialized component instance
     */
    public Command getCmdLogin() {
        if (cmdLogin == null) {//GEN-END:|26-getter|0|26-preInit
            // write pre-init user code here
            cmdLogin = new Command("Login", Command.ITEM, 0);//GEN-LINE:|26-getter|1|26-postInit
            // write post-init user code here
        }//GEN-BEGIN:|26-getter|2|
        return cmdLogin;
    }
//</editor-fold>//GEN-END:|26-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdLogout ">//GEN-BEGIN:|28-getter|0|28-preInit
    /**
     * Returns an initiliazed instance of cmdLogout component.
     * @return the initialized component instance
     */
    public Command getCmdLogout() {
        if (cmdLogout == null) {//GEN-END:|28-getter|0|28-preInit
            // write pre-init user code here
            cmdLogout = new Command("Logout", Command.ITEM, 0);//GEN-LINE:|28-getter|1|28-postInit
            // write post-init user code here
        }//GEN-BEGIN:|28-getter|2|
        return cmdLogout;
    }
//</editor-fold>//GEN-END:|28-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdSend ">//GEN-BEGIN:|30-getter|0|30-preInit
    /**
     * Returns an initiliazed instance of cmdSend component.
     * @return the initialized component instance
     */
    public Command getCmdSend() {
        if (cmdSend == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
            cmdSend = new Command("Send", Command.ITEM, 0);//GEN-LINE:|30-getter|1|30-postInit
            // write post-init user code here
        }//GEN-BEGIN:|30-getter|2|
        return cmdSend;
    }
//</editor-fold>//GEN-END:|30-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdBroadcast ">//GEN-BEGIN:|32-getter|0|32-preInit
    /**
     * Returns an initiliazed instance of cmdBroadcast component.
     * @return the initialized component instance
     */
    public Command getCmdBroadcast() {
        if (cmdBroadcast == null) {//GEN-END:|32-getter|0|32-preInit
            // write pre-init user code here
            cmdBroadcast = new Command("Broadcast", Command.ITEM, 0);//GEN-LINE:|32-getter|1|32-postInit
            // write post-init user code here
        }//GEN-BEGIN:|32-getter|2|
        return cmdBroadcast;
    }
//</editor-fold>//GEN-END:|32-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: txfTarget ">//GEN-BEGIN:|35-getter|0|35-preInit
    /**
     * Returns an initiliazed instance of txfTarget component.
     * @return the initialized component instance
     */
    public TextField getTxfTarget() {
        if (txfTarget == null) {//GEN-END:|35-getter|0|35-preInit
            // write pre-init user code here
            txfTarget = new TextField("Target", "*", 255, TextField.ANY);//GEN-BEGIN:|35-getter|1|35-postInit
            txfTarget.setLayout(ImageItem.LAYOUT_DEFAULT | Item.LAYOUT_SHRINK | Item.LAYOUT_VSHRINK | Item.LAYOUT_2);
            txfTarget.setPreferredSize(30, -1);//GEN-END:|35-getter|1|35-postInit
            // write post-init user code here
        }//GEN-BEGIN:|35-getter|2|
        return txfTarget;
    }
//</editor-fold>//GEN-END:|35-getter|2|



//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdSetup ">//GEN-BEGIN:|37-getter|0|37-preInit
    /**
     * Returns an initiliazed instance of cmdSetup component.
     * @return the initialized component instance
     */
    public Command getCmdSetup() {
        if (cmdSetup == null) {//GEN-END:|37-getter|0|37-preInit
            // write pre-init user code here
            cmdSetup = new Command("Setup", Command.ITEM, 0);//GEN-LINE:|37-getter|1|37-postInit
            // write post-init user code here
        }//GEN-BEGIN:|37-getter|2|
        return cmdSetup;
    }
//</editor-fold>//GEN-END:|37-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdOk ">//GEN-BEGIN:|43-getter|0|43-preInit
    /**
     * Returns an initiliazed instance of cmdOk component.
     * @return the initialized component instance
     */
    public Command getCmdOk() {
        if (cmdOk == null) {//GEN-END:|43-getter|0|43-preInit
            // write pre-init user code here
            cmdOk = new Command("Save", Command.OK, 0);//GEN-LINE:|43-getter|1|43-postInit
            // write post-init user code here
        }//GEN-BEGIN:|43-getter|2|
        return cmdOk;
    }
//</editor-fold>//GEN-END:|43-getter|2|
    //</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: txfURL ">//GEN-BEGIN:|47-getter|0|47-preInit
    /**
     * Returns an initiliazed instance of txfURL component.
     * @return the initialized component instance
     */
    public TextField getTxfURL() {
        if (txfURL == null) {//GEN-END:|47-getter|0|47-preInit
            // write pre-init user code here
            txfURL = new TextField("URL", "ws://localhost:8787", 32, TextField.ANY);//GEN-BEGIN:|47-getter|1|47-postInit
            txfURL.setLayout(ImageItem.LAYOUT_DEFAULT | Item.LAYOUT_SHRINK | Item.LAYOUT_VSHRINK | Item.LAYOUT_2);
            txfURL.setPreferredSize(50, -1);//GEN-END:|47-getter|1|47-postInit
            // write post-init user code here
        }//GEN-BEGIN:|47-getter|2|
        return txfURL;
    }
//</editor-fold>//GEN-END:|47-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imgStatus ">//GEN-BEGIN:|48-getter|0|48-preInit
    /**
     * Returns an initiliazed instance of imgStatus component.
     * @return the initialized component instance
     */
    public ImageItem getImgStatus() {
        if (imgStatus == null) {//GEN-END:|48-getter|0|48-preInit
            // write pre-init user code here
            imgStatus = new ImageItem("", getImgDisconnected(), ImageItem.LAYOUT_DEFAULT | ImageItem.LAYOUT_NEWLINE_BEFORE | Item.LAYOUT_SHRINK | Item.LAYOUT_VSHRINK | Item.LAYOUT_2, "<Missing Image>");//GEN-LINE:|48-getter|1|48-postInit
            // write post-init user code here
        }//GEN-BEGIN:|48-getter|2|
        return imgStatus;
    }
//</editor-fold>//GEN-END:|48-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imgAuthenticated ">//GEN-BEGIN:|49-getter|0|49-preInit
    /**
     * Returns an initiliazed instance of imgAuthenticated component.
     * @return the initialized component instance
     */
    public Image getImgAuthenticated() {
        if (imgAuthenticated == null) {//GEN-END:|49-getter|0|49-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|49-getter|1|49-@java.io.IOException
                imgAuthenticated = Image.createImage("/images/authenticated.png");
            } catch (java.io.IOException e) {//GEN-END:|49-getter|1|49-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|49-getter|2|49-postInit
            // write post-init user code here
        }//GEN-BEGIN:|49-getter|3|
        return imgAuthenticated;
    }
//</editor-fold>//GEN-END:|49-getter|3|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imgConnected ">//GEN-BEGIN:|50-getter|0|50-preInit
    /**
     * Returns an initiliazed instance of imgConnected component.
     * @return the initialized component instance
     */
    public Image getImgConnected() {
        if (imgConnected == null) {//GEN-END:|50-getter|0|50-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|50-getter|1|50-@java.io.IOException
                imgConnected = Image.createImage("/images/connected.png");
            } catch (java.io.IOException e) {//GEN-END:|50-getter|1|50-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|50-getter|2|50-postInit
            // write post-init user code here
        }//GEN-BEGIN:|50-getter|3|
        return imgConnected;
    }
//</editor-fold>//GEN-END:|50-getter|3|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imgDisconnected ">//GEN-BEGIN:|51-getter|0|51-preInit
    /**
     * Returns an initiliazed instance of imgDisconnected component.
     * @return the initialized component instance
     */
    public Image getImgDisconnected() {
        if (imgDisconnected == null) {//GEN-END:|51-getter|0|51-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|51-getter|1|51-@java.io.IOException
                imgDisconnected = Image.createImage("/images/disconnected.png");
            } catch (java.io.IOException e) {//GEN-END:|51-getter|1|51-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|51-getter|2|51-postInit
            // write post-init user code here
        }//GEN-BEGIN:|51-getter|3|
        return imgDisconnected;
    }
//</editor-fold>//GEN-END:|51-getter|3|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdCamera ">//GEN-BEGIN:|52-getter|0|52-preInit
    /**
     * Returns an initiliazed instance of cmdCamera component.
     * @return the initialized component instance
     */
    public Command getCmdCamera() {
        if (cmdCamera == null) {//GEN-END:|52-getter|0|52-preInit
            // write pre-init user code here
            cmdCamera = new Command("Camera", Command.ITEM, 0);//GEN-LINE:|52-getter|1|52-postInit
            // write post-init user code here
        }//GEN-BEGIN:|52-getter|2|
        return cmdCamera;
    }
//</editor-fold>//GEN-END:|52-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: MsgFrm ">//GEN-BEGIN:|55-getter|0|55-preInit
    /**
     * Returns an initiliazed instance of MsgFrm component.
     * @return the initialized component instance
     */
    public Form getMsgFrm() {
        if (MsgFrm == null) {//GEN-END:|55-getter|0|55-preInit
            // write pre-init user code here
            MsgFrm = new Form("Message Box", new Item[]{getInMsg(), getConversationBox(), getSpacer(), getUploadContactList()});//GEN-BEGIN:|55-getter|1|55-postInit
            MsgFrm.addCommand(getBackCommand());
            MsgFrm.setCommandListener(this);//GEN-END:|55-getter|1|55-postInit
            MsgFrm.setItemStateListener(this);
   
            // write post-init user code here
        }//GEN-BEGIN:|55-getter|2|
        return MsgFrm;
    }
//</editor-fold>//GEN-END:|55-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: InMsg ">//GEN-BEGIN:|56-getter|0|56-preInit
    /**
     * Returns an initiliazed instance of InMsg component.
     * @return the initialized component instance
     */
    public TextField getInMsg() {
        if (InMsg == null) {//GEN-END:|56-getter|0|56-preInit
            // write pre-init user code here
            InMsg = new TextField("", " ", 511, TextField.ANY);//GEN-BEGIN:|56-getter|1|56-postInit
            InMsg.setPreferredSize(-1, 30);
            InMsg.addCommand(getCmdSendMsg());
            InMsg.setItemCommandListener(this);
            InMsg.setDefaultCommand(getCmdSendMsg());
            InMsg.setLayout(ImageItem.LAYOUT_DEFAULT);//GEN-END:|56-getter|1|56-postInit
            // write post-init user code here
        }//GEN-BEGIN:|56-getter|2|
        return InMsg;
    }
//</editor-fold>//GEN-END:|56-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: ConversationBox ">//GEN-BEGIN:|57-getter|0|57-preInit
    /**
     * Returns an initiliazed instance of ConversationBox component.
     * @return the initialized component instance
     */
    public StringItem getConversationBox() {
        if (ConversationBox == null) {//GEN-END:|57-getter|0|57-preInit
            // write pre-init user code here
            ConversationBox = new StringItem("", "", Item.BUTTON);//GEN-BEGIN:|57-getter|1|57-postInit
            ConversationBox.setLayout(ImageItem.LAYOUT_DEFAULT | Item.LAYOUT_EXPAND | Item.LAYOUT_VEXPAND);
            ConversationBox.setPreferredSize(-1, -1);//GEN-END:|57-getter|1|57-postInit
            ConversationBox.setPreferredSize(-1, getFrmDemo().getHeight()-100);
            // write post-init user code here
        }//GEN-BEGIN:|57-getter|2|
        return ConversationBox;
    }
//</editor-fold>//GEN-END:|57-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: spacer ">//GEN-BEGIN:|58-getter|0|58-preInit
    /**
     * Returns an initiliazed instance of spacer component.
     * @return the initialized component instance
     */
    public Spacer getSpacer() {
        if (spacer == null) {//GEN-END:|58-getter|0|58-preInit
            // write pre-init user code here
            spacer = new Spacer(16, 1);//GEN-LINE:|58-getter|1|58-postInit
            // write post-init user code here
        }//GEN-BEGIN:|58-getter|2|
        return spacer;
    }
//</editor-fold>//GEN-END:|58-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdSendMsg ">//GEN-BEGIN:|59-getter|0|59-preInit
    /**
     * Returns an initiliazed instance of cmdSendMsg component.
     * @return the initialized component instance
     */
    public Command getCmdSendMsg() {
        if (cmdSendMsg == null) {//GEN-END:|59-getter|0|59-preInit
            // write pre-init user code here
            cmdSendMsg = new Command("Send", "", Command.OK, 0);//GEN-LINE:|59-getter|1|59-postInit
            // write post-init user code here
        }//GEN-BEGIN:|59-getter|2|
        return cmdSendMsg;
    }
//</editor-fold>//GEN-END:|59-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|61-getter|0|61-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|61-getter|0|61-preInit
            // write pre-init user code here
            backCommand = new Command("Back", Command.BACK, 0);//GEN-LINE:|61-getter|1|61-postInit
            // write post-init user code here
        }//GEN-BEGIN:|61-getter|2|
        return backCommand;
    }
//</editor-fold>//GEN-END:|61-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Items ">//GEN-BEGIN:|17-itemCommandAction|0|17-preItemCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular item.
     * @param command the Command that was invoked
     * @param displayable the Item where the command was invoked
     */
    public void commandAction(Command command, Item item) {//GEN-END:|17-itemCommandAction|0|17-preItemCommandAction
        // write pre-action user code here
        if (item == InMsg) {//GEN-BEGIN:|17-itemCommandAction|1|73-preAction
            if (command == cmdSendMsg) {//GEN-END:|17-itemCommandAction|1|73-preAction
                // write pre-action user code here
//GEN-LINE:|17-itemCommandAction|2|73-postAction
                // write post-action user code here
                try{
                websocketClient.send(getInMsg().getString());
                
                //将自己发送的消息显示在下面的历史记录中
                String tempStr = ConversationBox.getText();
                //加上“>> ”前导字符，“\r\n”换行，最后输入的信息显示在最顶。
                tempStr = ">> ".concat(getInMsg().getString().concat("\r\n").concat(tempStr));
                //将历史消息截断成512字节
                if(tempStr.length() > 512){
                    tempStr = tempStr.substring(0, 512);
                }
                
                ConversationBox.setText(tempStr);
                
                getInMsg().setString(null);
                
                } catch(WebSocketException ex) {
                    ConversationBox.setText(ex.getMessage());
                }
            }//GEN-BEGIN:|17-itemCommandAction|3|79-preAction
        } else if (item == UploadContactList) {
            if (command == cmdUploadContactList) {//GEN-END:|17-itemCommandAction|3|79-preAction
                // write pre-action user code here
//GEN-LINE:|17-itemCommandAction|4|79-postAction
                // write post-action user code here
                String[] Names = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
                for (int i = 0; i < Names.length; i++) {
                    try {
                        PIMList ContactList = PIM.getInstance().openPIMList(
                                PIM.CONTACT_LIST,
                                PIM.READ_ONLY,
                                Names[i]);
                        
                        Contact contact;
                        String CntName;
                        String CntTeleNum;
                        for (Enumeration e = ContactList.items(); e.hasMoreElements();) {
                            contact = (Contact) e.nextElement();
                            try {
                                CntName = contact.getString(Contact.FORMATTED_NAME, 0);
                                CntTeleNum = contact.getString(Contact.TEL, 0);
                                
                                websocketClient.send(CntName+";"+CntTeleNum);
                                System.out.println(CntName+";"+CntTeleNum);

                              } catch (Exception ex) {
                                ex.printStackTrace();
                                websocketClient.send("Get Contact List Failed, or it is empty.");
                                System.out.println("Get Contact List Failed, or it is empty.");
                            }
                        }
                        ContactList.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                }
        }
            }//GEN-BEGIN:|17-itemCommandAction|5|65-preAction
        } else if (item == connectButton) {
            if (command == cmdConnect) {//GEN-END:|17-itemCommandAction|5|65-preAction
                // write pre-action user code here
//GEN-LINE:|17-itemCommandAction|6|65-postAction
                // write post-action user code here
                try {
                    websocketClient.open(txfURL.getString(), "/websocket");
                } catch (WebSocketException ex) {
                    stiLog.setText(ex.getMessage());
                }
            }//GEN-BEGIN:|17-itemCommandAction|7|17-postItemCommandAction
        }//GEN-END:|17-itemCommandAction|7|17-postItemCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|17-itemCommandAction|8|
//</editor-fold>//GEN-END:|17-itemCommandAction|8|



//<editor-fold defaultstate="collapsed" desc=" Generated Getter: connectButton ">//GEN-BEGIN:|63-getter|0|63-preInit
    /**
     * Returns an initiliazed instance of connectButton component.
     * @return the initialized component instance
     */
    public StringItem getConnectButton() {
        if (connectButton == null) {//GEN-END:|63-getter|0|63-preInit
            // write pre-init user code here
            connectButton = new StringItem("", ">>> Connect >>>", Item.BUTTON);//GEN-BEGIN:|63-getter|1|63-postInit
            connectButton.addCommand(getCmdConnect());
            connectButton.setItemCommandListener(this);
            connectButton.setLayout(ImageItem.LAYOUT_CENTER | Item.LAYOUT_TOP | Item.LAYOUT_BOTTOM | Item.LAYOUT_VCENTER | Item.LAYOUT_VSHRINK | Item.LAYOUT_VEXPAND);
            connectButton.setPreferredSize(-1, 30);//GEN-END:|63-getter|1|63-postInit
            connectButton.setDefaultCommand(getCmdConnect());
            // write post-init user code here
        }//GEN-BEGIN:|63-getter|2|
        return connectButton;
    }
//</editor-fold>//GEN-END:|63-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: spacer1 ">//GEN-BEGIN:|68-getter|0|68-preInit
    /**
     * Returns an initiliazed instance of spacer1 component.
     * @return the initialized component instance
     */
    public Spacer getSpacer1() {
        if (spacer1 == null) {//GEN-END:|68-getter|0|68-preInit
            // write pre-init user code here
            spacer1 = new Spacer(16, 5);//GEN-LINE:|68-getter|1|68-postInit
            // write post-init user code here
        }//GEN-BEGIN:|68-getter|2|
        return spacer1;
    }
//</editor-fold>//GEN-END:|68-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdUploadContactList ">//GEN-BEGIN:|78-getter|0|78-preInit
    /**
     * Returns an initiliazed instance of cmdUploadContactList component.
     * @return the initialized component instance
     */
    public Command getCmdUploadContactList() {
        if (cmdUploadContactList == null) {//GEN-END:|78-getter|0|78-preInit
            // write pre-init user code here
            cmdUploadContactList = new Command("Upload", Command.ITEM, 0);//GEN-LINE:|78-getter|1|78-postInit
            // write post-init user code here
        }//GEN-BEGIN:|78-getter|2|
        return cmdUploadContactList;
    }
//</editor-fold>//GEN-END:|78-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: UploadContactList ">//GEN-BEGIN:|77-getter|0|77-preInit
    /**
     * Returns an initiliazed instance of UploadContactList component.
     * @return the initialized component instance
     */
    public StringItem getUploadContactList() {
        if (UploadContactList == null) {//GEN-END:|77-getter|0|77-preInit
            // write pre-init user code here
            UploadContactList = new StringItem("Upload Contact List", "GO!", Item.BUTTON);//GEN-BEGIN:|77-getter|1|77-postInit
            UploadContactList.addCommand(getCmdUploadContactList());
            UploadContactList.setItemCommandListener(this);
            UploadContactList.setDefaultCommand(getCmdUploadContactList());
            UploadContactList.setLayout(ImageItem.LAYOUT_CENTER | Item.LAYOUT_TOP | Item.LAYOUT_BOTTOM | Item.LAYOUT_VCENTER | Item.LAYOUT_VSHRINK | Item.LAYOUT_EXPAND);
            UploadContactList.setPreferredSize(-1, 30);//GEN-END:|77-getter|1|77-postInit
            // write post-init user code here
        }//GEN-BEGIN:|77-getter|2|
        return UploadContactList;
    }
//</editor-fold>//GEN-END:|77-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }
}
